package com.haibara.aiojcodesandbox.controller;


import cn.hutool.core.io.FileUtil;
import com.haibara.aiojcodesandbox.core.CodeSandboxFactory;
import com.haibara.aiojcodesandbox.core.CodeSandboxTemplate;
import com.haibara.aiojcodesandbox.model.ExecuteCodeRequest;
import com.haibara.aiojcodesandbox.model.ExecuteCodeResponse;
import com.haibara.aiojcodesandbox.model.QuestionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.charset.StandardCharsets;
@Slf4j
@RestController
@RequestMapping("/codesandbox")
public class CodeSandboxController {

    @PostMapping("/execute")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest) {
        log.info("判题:{}",executeCodeRequest);
        CodeSandboxTemplate sandboxTemplate = CodeSandboxFactory.getInstance(executeCodeRequest.getLanguage());
        return sandboxTemplate.executeCode(executeCodeRequest);
    }

    @PostMapping("/getCode")
    public String getCode(@RequestBody QuestionCode questionCode){
        log.info("开始创建judgeCode:{}",questionCode);
        Long questionId = questionCode.getQuestionId();
        String code = questionCode.getCode();
        String globalCodePath = System.getProperty("user.dir") + File.separator + "judgeCode";
        String userCodePath = globalCodePath+FileUtil.FILE_SEPARATOR+"question_"+questionId+".java";
        File file = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return "ok";
    }
}
